package controllers

import (
	"strings"

	"github.com/gin-gonic/gin"
	"jihe.common/protos/user_server"
	"jihe.common/protos/user_server/proto"
	"jihe.common/resp"
	"jihe.common/tool"
)

type UserController struct {
}

func (s *UserController) SubmitAudit(c *gin.Context) {
	req := proto.UserDUserAudit{}
	err := c.BindJSON(&req)
	if err != nil {
		resp.RespParamErr(c)
		return
	}
	if req.Phone == "" || req.Addr == "" || req.Introduction == "" {
		resp.RespParamErr(c)
		return
	}
	if !tool.VerifyIdName(req.IdCard, req.Realname) {
		resp.RespGeneralErr(c, "身份信息不正确")
		return
	}
	req.Uid = getUid(c)
	_, err = user_server.UserSubmitAudit(c, &req)
	if err != nil {
		if strings.Contains(err.Error(), "d_user_audits_id_card_uindex") {
			resp.RespGeneralErr(c, "身份证已被认证过")
			return
		}
		resp.RespInternalErr(c)
		return
	}
	resp.RespOk(c)
}

func (s *UserController) GetUserAuditDetail(c *gin.Context) {
	uid := c.Query("uid")
	if uid == "" {
		uid = getUid(c)
	}
	ret, err := user_server.UserGetAuditByUids(c, &proto.UserGetAuditByUidsReq{
		Uids: uid,
	})
	if err != nil {
		resp.RespInternalErr(c)
		return
	}
	if len(ret.List) == 0 {
		resp.RespOk(c, nil)
		return
	}
	resp.RespOk(c, ret.List[0])
}

func (s *UserController) GetUserInfoById(c *gin.Context) {
	uid := c.Query("uid")
	if uid == "" {
		resp.RespParamErr(c)
		return
	}
	ret, err := user_server.UserGetByUid(c, &proto.UserDUser{
		Id: uid,
	})
	if err != nil {
		resp.RespInternalErr(c)
		return
	}
	resp.RespOk(c, ret)
}

func (s *UserController) UpdateDiscount(c *gin.Context) {
	req := proto.UserUser{}
	err := c.BindJSON(&req)
	if err != nil {
		resp.RespParamErr(c)
		return
	}
	req.Uid = getUid(c)
	if req.Discount <= 0 {
		resp.RespParamErr(c)
		return
	}
	_, err = user_server.UserUpdateUserById(c, &req)
	if err != nil {
		resp.RespParamErr(c)
		return
	}
	resp.RespOk(c)
}

func (s *UserController) GetDiscount(c *gin.Context) {
	req := proto.UserGetUserByIdsReq{
		Uids: []string{getUid(c)},
	}
	ret, err := user_server.UserGetUserByIds(c, &req)
	if err != nil {
		resp.RespInternalErr(c, err.Error())
		return
	}
	if len(ret.List) != 0 {
		resp.RespOk(c, ret.List[0])
		return
	}
	resp.RespOk(c)
}

func (s *UserController) GetAmount(c *gin.Context) {
	ret, err := user_server.UserGetAmount(c, &proto.UserAccount{Uid: getUid(c)})
	if err != nil {
		resp.RespInternalErr(c, err.Error())
		return
	}
	resp.RespOk(c, ret)
}
